<!--
 * @Description: 
 * @Author: 胡涛
 * @Date: 2023-09-20 14:32:31
 * @LastEditors: 胡涛
 * @LastEditTime: 2023-11-30 00:46:03
-->
<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
      :mode="mode"
    />
    <Editor
      style="height: 500px; overflow-y: hidden"
      v-model="editorValue"
      :defaultConfig="editorConfig"
      :mode="mode"
      @onCreated="handleCreated"
      @onChange="handleChanged"
    />
  </div>
</template>

<script lang="ts" setup>
import "@wangeditor/editor/dist/css/style.css"; // 引入 css
import { onBeforeUnmount, ref, shallowRef, onMounted, watch } from "vue";
import { Editor, Toolbar } from "@wangeditor/editor-for-vue";
import { IToolbarConfig, IEditorConfig } from "@wangeditor/editor";

type HtmlEditorProps = {
  value: string;
  mode: "default" | "simple";
  toolbarConfig: Partial<IToolbarConfig>;
  editorConfig: Partial<IEditorConfig>;
};

const props = withDefaults(defineProps<HtmlEditorProps>(), {
  value: "",
  mode: "default",
  toolbarConfig: () => {
    return {};
  },
  editorConfig: () => {
    {
      return { placeholder: "请输入内容..." };
    }
  },
});

const emits = defineEmits(["update:value", "change"]);
const emiting = ref(false);
const editorRef = shallowRef();
const editorValue = ref("");
watch(
  () => props.value,
  () => {
    if (!emiting.value) {
      editorValue.value = props.value;
    }
  }
);

onMounted(() => {});

onBeforeUnmount(() => {
  const editor = editorRef.value;
  if (editor == null) return;
  editor.destroy();
});

const handleCreated = (editor) => {
  editorRef.value = editor;
};

const timeout = ref();
const handleChanged = (value: string) => {
  emiting.value = true;
  emits("update:value", editorValue.value);
  emits("change", editorValue.value);
  timeout.value && clearTimeout(timeout.value);
  timeout.value = setTimeout(() => {
    emiting.value = false;
  }, 100);
};
</script>

<style lang="less" scoped></style>
